package jmind.core.support;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import jmind.core.log.LogUtil;
import jmind.core.util.DataUtil;

import org.apache.commons.beanutils.PropertyUtils;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class Collections {

    public static List<Long> toLongList(List<String> array) {
        return Lists.transform(array, new Function<String, Long>() {
            @Override
            public Long apply(String input) {
                return DataUtil.toLong(input);
            }
        });
    }

    public static List<Integer> toIntegerList(List<String> array) {

        return Lists.transform(array, new Function<String, Integer>() {
            @Override
            public Integer apply(String input) {
                return DataUtil.toInt(input);
            }
        });
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> getPropertys(Collection<?> list, String name) {
        List<T> a = Lists.newArrayList();
        try {
            for (Object obj : list) {
                //   BeanUtils.getProperty(obj, name);           
                T object = (T) PropertyUtils.getProperty(obj, name);
                a.add(object);
            }
        } catch (Exception e) {
            LogUtil.error(e);
        }
        return a;
    }

    @SuppressWarnings("unchecked")
    public static <A, B> Map<A, B> uniqueIndex(List<B> list, final String name) {
        return Maps.uniqueIndex(list, new Function<B, A>() {
            @Override
            public A apply(B obj) {
                try {
                    return (A) PropertyUtils.getProperty(obj, name);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
        });

    }

}
